package com.club.common.security;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.club.common.constant.JwtConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.nio.charset.Charset;

/**
 * 自定义的 passWord 解析器
 *
 * @author zhangfc
 * @date 2022/10/21 9:50
 */
@Component
@Slf4j
public class MyPasswordEncoder implements PasswordEncoder {

    /**
     * 对密码进行编码
     *
     * @param charSequence 要存储的密码
     * @return 编码后的密码
     */
    @Override
    public String encode(CharSequence charSequence) {
        //将密码进行MD5加密处理
        return DigestUtil.md5Hex(JwtConstant.MD5_KEY + charSequence.toString(), Charset.defaultCharset());
    }

    /**
     * 匹配密码规则
     *
     * @param charSequence 客户端传入的密码
     * @param s            存储的密码
     * @return true Or false
     */
    @Override
    public boolean matches(CharSequence charSequence, String s) {
        log.info(DigestUtil.md5Hex(JwtConstant.MD5_KEY + charSequence.toString(), Charset.defaultCharset()) + "------" + s);
        return StrUtil.equals(s, DigestUtil.md5Hex(JwtConstant.MD5_KEY + charSequence.toString(), Charset.defaultCharset()));
    }

    @Override
    public boolean upgradeEncoding(String encodedPassword) {
        return false;
    }
}
